package com.glodon.fansi.webui.controller;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.glodon.fansi.common.AjaxResult;
import com.glodon.fansi.db.model.User;
import com.glodon.fansi.db.model.WbLogin;
import com.glodon.fansi.service.UserService;
import com.glodon.fansi.service.WbLoginService;
import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.javabeans.qzone.UserInfoBean;
import com.qq.connect.oauth.Oauth;

@Controller
public class IndexController {
	private static Logger logger = LoggerFactory.getLogger(IndexController.class);
	@Autowired
	private WbLoginService wbLoginService;
	@Autowired
	private UserService userService;
	@RequestMapping({ "/", "", "index" })
	public String index() {
		return "index";
	}

	@RequestMapping("/login")
	public String beforelogin() {
		return "login";
	}

	@RequestMapping("/api/qqlogin")
	public void qqlogin(HttpServletRequest request, HttpServletResponse response) {
		try {
			response.sendRedirect(new Oauth().getAuthorizeURL(request));
		} catch (QQConnectException e) {
			logger.error("QQ登录错误 {}", e.getMessage());
			;
		} catch (IOException e) {
			logger.error("/api/qqlogin错误 {}", e.getMessage());
			;
		}
	}

	@RequestMapping("/api/qqlogincallback")
	public String qqlogincallback(HttpServletRequest request, HttpServletResponse response,ModelMap model) {
		try {
			AccessToken accessTokenObj = (new Oauth()).getAccessTokenByRequest(request);
			String accessToken = null;
			String openID = null;
			long tokenExpireIn = 0L;
			if (accessTokenObj.getAccessToken().equals("")) {
				// 我们的网站被CSRF攻击了或者用户取消了授权
				// 做一些数据统计工作
				logger.warn("没有获取到响应参数");
				return "redirect:/index";
			} else {
				accessToken = accessTokenObj.getAccessToken();
				tokenExpireIn = accessTokenObj.getExpireIn();
				// 利用获取到的accessToken 去获取当前用的openid -------- start
				OpenID openIDObj = new OpenID(accessToken);
				openID = openIDObj.getUserOpenID();
				UserInfo qzoneUserInfo = new UserInfo(accessToken, openID);
				UserInfoBean userInfoBean = qzoneUserInfo.getUserInfo();
				logger.debug("accessToken : {}", accessToken);
				logger.debug("openID : {}", openID);
				logger.debug("tokenExpireIn : {}", tokenExpireIn);
				logger.debug("tokenExpireIn : {}", tokenExpireIn);
				logger.debug("qzoneUserInfo : {}", JSON.toJSONString(qzoneUserInfo));
				logger.debug("userInfoBean : {}", JSON.toJSONString(userInfoBean));
				WbLogin wbLogin = wbLoginService.selectByOpenId(openID);
				if (wbLogin == null) {
					wbLogin = new WbLogin();
					wbLogin.setOpenId(openID);
					wbLogin.setCreatetime(new Date());
					wbLogin.setHeadPhoto(userInfoBean.getAvatar().getAvatarURL100());
					wbLogin.setNickname(userInfoBean.getNickname());
					wbLogin.setStatus(0);// 未完成绑定
					wbLogin.setType("qq");
					wbLoginService.insert(wbLogin);
				}
				int status = wbLogin.getStatus();
				if (status == 0 || StringUtils.isBlank(wbLogin.getUserId())) {
					wbLogin = wbLoginService.selectByOpenId(openID);
					model.put("wbLogin", wbLogin);
					return "binding";
				}
				User user = userService.selectById(wbLogin.getUserId());
				model.put("user", user);
				request.getSession().setAttribute("user", user);
				return "redirect:/index";
			}
		} catch (QQConnectException e) {
			logger.error("{}", e.getMessage());
		}
		return null;
	}
	@RequestMapping("/binding")
	public String binding(){
		return "binding";
	}
	@RequestMapping("/dobinding")
	@ResponseBody
	public AjaxResult dobinding(@RequestParam("id")Integer id,@RequestParam("account")String account,@RequestParam("openId")String openId,HttpSession session){
		User u = userService.selectByAccount(account);
		if(u==null){
			return AjaxResult.newError("用户名不存在");
		}
		WbLogin wbLogin = wbLoginService.selectByUserId(u.getId());
		if(wbLogin!=null){
			return AjaxResult.newError("该用户已经绑定过");
		}
		wbLogin = wbLoginService.selectByOpenId(openId);
		wbLogin.setUserId(u.getId());
		wbLogin.setStatus(1);
		wbLoginService.update(wbLogin);
		session.setAttribute("user", u);
		return AjaxResult.newSuccsess();
	}
}
